from app import db
from datetime import datetime

class User(db.Model):
    """用户表"""
    __tablename__ = 'users'
    
    id = db.Column(db.Integer, primary_key=True)
    unionid = db.Column(db.String(128), unique=True, nullable=False, comment='微信UnionID')
    openid = db.Column(db.String(128), nullable=True, comment='微信OpenID')
    nickname = db.Column(db.String(100), nullable=False, comment='用户昵称')
    avatar_url = db.Column(db.String(255), nullable=True, comment='头像URL')
    phone = db.Column(db.String(20), nullable=True, comment='手机号')
    email = db.Column(db.String(100), nullable=True, comment='邮箱')
    vip_level = db.Column(db.Integer, default=0, comment='VIP等级，0=普通用户')
    daily_quota = db.Column(db.Integer, default=5, comment='每日生成次数限制')
    used_quota = db.Column(db.Integer, default=0, comment='今日已使用次数')
    quota_reset_date = db.Column(db.Date, default=datetime.now().date, comment='配额重置日期')
    is_active = db.Column(db.Boolean, default=True, comment='是否激活')
    created_at = db.Column(db.DateTime, default=datetime.utcnow, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')
    
    # 关联关系
    image_tasks = db.relationship('ImageTask', backref='user', lazy=True)
    
    def __repr__(self):
        return f'<User {self.nickname}>'
    
    def to_dict(self):
        return {
            'id': self.id,
            'nickname': self.nickname,
            'avatar_url': self.avatar_url,
            'vip_level': self.vip_level,
            'daily_quota': self.daily_quota,
            'used_quota': self.used_quota,
            'created_at': self.created_at.isoformat() if self.created_at else None
        }
    
    def reset_daily_quota(self):
        """重置每日配额"""
        today = datetime.now().date()
        if self.quota_reset_date < today:
            self.used_quota = 0
            self.quota_reset_date = today
            db.session.commit()
    
    def can_generate(self):
        """检查用户是否还能生成图片"""
        self.reset_daily_quota()
        return self.used_quota < self.daily_quota